package com.wisdytech.ccdserver.bucket.serveice.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wisdytech.ccdserver.bucket.dao.IBucketTaskDao;
import com.wisdytech.ccdserver.bucket.dto.*;
import com.wisdytech.ccdserver.bucket.model.BucketRecord;
import com.wisdytech.ccdserver.bucket.model.BucketTask;
import com.wisdytech.ccdserver.bucket.serveice.IBucketRecordService;
import com.wisdytech.ccdserver.bucket.serveice.IBucketTaskService;
import com.wisdytech.ccdserver.common.contants.CommonConstants;
import com.wisdytech.ccdserver.common.utils.DateUtils;
import com.wisdytech.common.bean.BasePage;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.bean.MultiResultResponse;
import com.wisdytech.common.bean.UniqueResultResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;


@Slf4j
public class BucketTaskServiceImpl extends ServiceImpl<IBucketTaskDao, BucketTask> implements IBucketTaskService {
    @Autowired
    private IBucketRecordService bucketRecordService;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    /**
     * @Description: 保存一条任务数据
     * @Param: * @param filter
     * @return: * @return com.wisdytech.common.bean.UniqueResultResponse
     * @Author: SV00216491
     * @Date: 2024/4/22  10:46
     */

    @Override
    public void saveBucketTask(Filter filter, String taskid) {
        //保存任务明细
        Map<String, Object> queryMap = filter.getQueryMap();
        BucketTask bucketTask = new BucketTask();
        String queryParams = filter.getQueryParams();
        if (!StringUtils.isEmpty(queryParams)) {
            bucketTask.setTaskParams(queryParams);
        }
        String taskName = (String) queryMap.get("taskName");
        bucketTask.setId(taskid);
        bucketTask.setTaskName(taskName);
        bucketTask.setDelFlag(CommonConstants.DEL_FALSE);
        bucketTask.setInterruptFlag(CommonConstants.INTERRUPT_FALSE);
        bucketTask.setOkFlag(CommonConstants.OK_FALSE);
        bucketTask.setCreateDate(new Date());
        String username = RpcContext.getServiceContext().getAttachment("username");
        bucketTask.setCreateUser(username);
        this.save(bucketTask);
    }

    public int srarchPushtasks(Filter filter) {
        //前端的条件
        String taskName = (String) filter.getQueryMap().get("taskName");
        QueryWrapper<BucketTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("TASK_NAME", taskName);
        queryWrapper.apply(" JSON_CONTAINS(TASK_PARAMS,'" + filter.getQueryParams() + "')");
        return this.baseMapper.selectCount(queryWrapper);
    }

    public String checkBucketIsNull(Filter filter) {
        //前端的条件
        String taskName = (String) filter.getQueryMap().get("equipmentCode");
        List<String> bucketstr = Arrays.asList(taskName.split(","));
        String prefix = "ccd_bucket_";
        List<TableBuckets> buckets = bucketstr.stream().map(s -> {
            TableBuckets tableBucket = new TableBuckets();
            String tableName = prefix + s.toLowerCase();
            tableBucket.setTableName(tableName);
            return tableBucket;
        }).collect(Collectors.toList());
        List<TableBuckets> tableBuckets = this.baseMapper.customerSearchBuckets();
        List<TableBuckets> subtract = (List<TableBuckets>) org.apache.commons.collections.CollectionUtils.subtract(buckets, tableBuckets);
        String strBucket = subtract.stream().map(br -> br.getTableName()).collect(Collectors.joining(","));
        return strBucket;
    }


    public static void main(String[] args) {
        String taskName = "JT03-QD-L1-08,jt03-qd-l3-02";
        List<String> buckets = Arrays.asList(taskName.split(","));
        String prefix = "CCD_BUCKET_";
        String collect = buckets.stream()
                .map(s -> "'" + prefix + s.toUpperCase() + "'")
                .collect(Collectors.joining(","));
        System.out.println();
    }


//    public UniqueResultResponse deleteBucketTaskByIds(List<String> ids) {
//        BucketTask bucketTask = new BucketTask();
//        String username = RpcContext.getServiceContext().getAttachment("username");
//        if (CollectionUtils.isEmpty(ids)) {
//            return UniqueResultResponse.fail("请选择相应的数据");
//        }
//        List<BucketTask> bucketLists = ids.stream().map(b -> {
//            bucketTask.setId(b);
//            bucketTask.setDelFlag(CommonConstants.DEL_TRUE);
//            bucketTask.setUpdateUser(username);
//            bucketTask.setUpdateDate(new Date());
//            return bucketTask;
//        }).collect(Collectors.toList());
//        this.updateBatchById(bucketLists);
//        return UniqueResultResponse.success(true);
//    }

    // 直接所有数据
    @Override
    public UniqueResultResponse deleteBucketTaskByIds(Filter filter) {
        String idStr = (String) filter.getQueryMap().get("ids");
        if (StringUtils.isEmpty(idStr)) {
            return UniqueResultResponse.fail("请选择相应的数据");
        }
        List<String> ids = Arrays.asList(idStr.split(","));

        //删除任务
        deleteTaskByIds(ids);
        //保存的动作异步处理
        CompletableFuture.runAsync(() -> {
            log.info("删除明细子线程-->" + Thread.currentThread().getName());
            //删除桶的详细记录
            bucketRecordService.deleteBucketDetailsByTaskIds(ids);
            //删除条件记录
            bucketRecordService.deleteBucketRecordsByTaskIds(ids);

        }, taskExecutor).whenComplete((res, ex) -> {
                    log.error("当前任务结果" + res);
                    if (ex != null) {
                        log.error("当前任务错误" + ex);
                    }
                }
        );
        return UniqueResultResponse.success(true);
    }


    @Override
    public void asyncBucketTaskByIds() {
        log.info("开始执行删除任务");
        List<BucketTaskDto> bucketTaskVos = asyncDealSearchOneDeatails();
        if (CollectionUtils.isEmpty(bucketTaskVos)) {
            return;
        }
        List<BucketTaskDto> readedbucketTaskDtos = bucketRecordService.searchBucketRecordByTaskid(bucketTaskVos);
        List<String> ids = readedbucketTaskDtos.stream().map(BucketTaskDto::getId).collect(Collectors.toList());
        log.info("删除任务的主键" + String.join(",", ids));
        List<BucketTask> deleteBucketList = checkTaskIsOk(ids);
        if (CollectionUtils.isEmpty(deleteBucketList)) {
            return;
        }
        List<String> deleteIds = deleteBucketList.stream().map(BucketTask::getId).collect(Collectors.toList());
        //删除桶的详细记录
        bucketRecordService.deleteBucketDetailsByTaskIds(deleteIds);
        //删除条件记录
        bucketRecordService.deleteBucketRecordsByTaskIds(deleteIds);
        //删除任务
        updateBatchTaskByIds(deleteIds);

    }

    public List<BucketTaskDto> asyncDealSearchOneDeatails() {
        String newDate = DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss");
        Date date = DateUtil.offset(DateUtil.parse(newDate), DateField.DAY_OF_MONTH, -2);
        String twoDaysAgo = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
        QueryWrapper<BucketTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DEL_FLAG", CommonConstants.DEL_FALSE);
        queryWrapper.le("CREATE_DATE", twoDaysAgo);
        queryWrapper.orderByAsc("CREATE_DATE");
        queryWrapper.last("limit 10");
        List<BucketTask> bucketTasks = this.baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(bucketTasks)) {
            return Collections.EMPTY_LIST;
        }
        List<BucketTaskDto> newBucketTaskVo = bucketTasks.stream().map(x -> {
            BucketTaskDto btv = new BucketTaskDto();
            BeanUtils.copyProperties(x, btv);
            return btv;
        }).collect(Collectors.toList());
        return newBucketTaskVo;
    }


    public List<BucketTask> checkTaskIsOk(List<String> ids) {
        QueryWrapper<BucketTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("PK_ID", ids);
        queryWrapper.eq("OK_FLAG", CommonConstants.OK_TRUE);
        queryWrapper.isNotNull("MBV");
        List<BucketTask> bucketTasks = this.baseMapper.selectList(queryWrapper);
        return bucketTasks;
    }

    public void updateBatchTaskByIds(List<String> ids) {
        String username = RpcContext.getServiceContext().getAttachment("username");
        List<BucketTask> bucketLists = ids.stream().map(b -> {
            BucketTask bucketTask = new BucketTask();
            bucketTask.setId(b);
            bucketTask.setDelFlag(CommonConstants.DEL_TRUE);
            bucketTask.setUpdateUser(username);
            bucketTask.setUpdateDate(new Date());
            return bucketTask;
        }).collect(Collectors.toList());
        this.updateBatchById(bucketLists);
    }


    public void deleteTaskByIds(List<String> ids) {
        this.baseMapper.deleteBatchIds(ids);
    }

    @Override
    public UniqueResultResponse interruptBucketTaskByIds(Filter filter) {
        String idStr = (String) filter.getQueryMap().get("ids");
        if (StringUtils.isEmpty(idStr)) {
            return UniqueResultResponse.fail("请选择相应的数据");
        }
        List<String> ids = Arrays.asList(idStr.split(","));
        String username = RpcContext.getServiceContext().getAttachment("username");
        if (CollectionUtils.isEmpty(ids)) {
            return UniqueResultResponse.fail("请选择相应的数据");
        }

        boolean b1 = checkBucketInterrupt(ids);
        if (!b1) {
            return UniqueResultResponse.fail("当前已选择的数据已经处于中断状态，请务重复点击");
        }

        List<BucketTask> bucketLists = ids.stream().map(b -> {
            BucketTask bucketTask = new BucketTask();
            bucketTask.setId(b);
            bucketTask.setInterruptFlag(CommonConstants.INTERRUPT_TRUE);
            bucketTask.setUpdateUser(username);
            bucketTask.setUpdateDate(new Date());
            return bucketTask;
        }).collect(Collectors.toList());
        this.updateBatchById(bucketLists);
        return UniqueResultResponse.success(true);
    }

    public boolean checkBucketInterrupt(List<String> ids) {
        QueryWrapper<BucketTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("PK_ID", ids);
        queryWrapper.eq("INTERRUPT_FLAG", CommonConstants.INTERRUPT_TRUE);
        Integer integer = this.baseMapper.selectCount(queryWrapper);
        if (integer > 0) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * @Description: 查看任务进度和检索进度。
     * @Param: * @param bucketTask
     * @return: * @return com.wisdytech.common.bean.UniqueResultResponse
     * @Author: SV00216491
     * @Date: 2024/4/23  13:18
     */

    @Override
    public MultiResultResponse findTaskAndSearchProgress(Filter filter) {
        Map<String, Object> queryMap = filter.getQueryMap();
        String taskName = (String) queryMap.get("taskName");
        String beginTime = (String) queryMap.get("beginTime");
        String endTime = (String) queryMap.get("endTime");
        Page<BucketTask> page = BasePage.getPage(filter);
        BucketTaskDto bucketTaskDto = new BucketTaskDto();
        if (!StringUtils.isEmpty(taskName)) {
            bucketTaskDto.setTaskName("%" + taskName + "%");
        }
        bucketTaskDto.setBeginTime(beginTime);
        bucketTaskDto.setEndTime(endTime);
        String username = RpcContext.getServiceContext().getAttachment("username");
        Long isAdminCount = this.baseMapper.checkIsAdmin(username);
        log.info("查询的用户名为" + username + "结果为" + isAdminCount);
        if (isAdminCount <= 0) {
            bucketTaskDto.setCreateUser(username);
        }
        IPage<BucketTaskDto> taskAndSearchProgress = this.baseMapper.findTaskAndSearchProgress(page, bucketTaskDto);
        //任务列表
        List<BucketTaskDto> list = taskAndSearchProgress.getRecords();
        // 根据任务获取对应的检索条件
        List<BucketTaskDto> bucketTaskDtos = bucketRecordService.searchBucketRecordByTaskid(list);
        taskAndSearchProgress.setRecords(bucketTaskDtos);
        return MultiResultResponse.success(taskAndSearchProgress);
    }


    @Override
    public void updateOkFlag(String taskId) {
        String username = RpcContext.getServiceContext().getAttachment("username");
        BucketTask bucketTask = new BucketTask();
        bucketTask.setId(taskId);
        bucketTask.setUpdateUser(username);
        bucketTask.setUpdateDate(new Date());
        bucketTask.setOkFlag(CommonConstants.OK_TRUE);
        this.updateById(bucketTask);
    }

    @Override
    public void updateInterRuptFlag(String taskId) {
        String username = RpcContext.getServiceContext().getAttachment("username");
        BucketTask bucketTask = new BucketTask();
        bucketTask.setId(taskId);
        bucketTask.setUpdateUser(username);
        bucketTask.setUpdateDate(new Date());
        bucketTask.setInterruptFlag(CommonConstants.INTERRUPT_FALSE);
        this.updateById(bucketTask);

    }

    @Override
    public void updateBucketTaskMbvByTaskId(BucketTaskDto bucketTaskDto, MinitorBucketViewDto mbv) {
        String id = bucketTaskDto.getId();
        Long pictureNum = mbv.getPictureNum();
        Long pictureTotalNum = mbv.getPictureTotalNum();
        Long searchNum = mbv.getSearchNum();
        Long searchTotalNum = mbv.getSearchTotalNum();

        if (pictureTotalNum.equals(pictureNum) && searchTotalNum.equals(searchNum)) {
            String newmbv = JSONObject.toJSON(mbv).toString();
            String username = RpcContext.getServiceContext().getAttachment("username");
            BucketTask bucketTask = new BucketTask();
            bucketTask.setId(id);
            bucketTask.setUpdateUser(username);
            bucketTask.setUpdateDate(new Date());
            bucketTask.setMbv(newmbv);
            this.updateById(bucketTask);
        }
    }


}
